//
//  KKUserAccountViewModel.swift
//  SinaWeiBo
//
//  Created by King.Kong. on 16/5/25.
//  Copyright © 2016年 King.Kong. All rights reserved.
//

import UIKit

private let userInfoKey = "cn.kingkong.userInfoKey"

class KKUserAccountViewModel: NSObject {
    
    static let sharedAccountViewModel:KKUserAccountViewModel = KKUserAccountViewModel()
    
    var userAccount:KKUserAccount?
    
    // 伪单例
    private override init() {
        super.init()
        
        userAccount = loadUserAccount()
    }
    
    // 定义计算下属性
    var userLogin: Bool {
        
        if userAccount?.expires_date?.compare(NSDate()) == .OrderedDescending {
                        return true
                    }
        //如果过期  需要将 userAccount 设置为 nil
        userAccount = nil
        return false
    }
    
    // 定义一个纯种的NSUrl
    var headURL: NSURL? {
        
        return NSURL(string: userAccount?.avatar_large ?? "")
    }
    
}

extension KKUserAccountViewModel {

    /// 处理网络请求
    func loadAccessToken(code:String,finished:((isSuccess: Bool) -> ())) {
        
        KKNetworkTools.sharedTools.loadAccessToken(code) { (responseObject, error) in
            
            if error != nil {
                print(error)
               
                finished(isSuccess: false)
                return
            }
            
            self.loadUserInfo(responseObject,finished: finished)
        }
        
    }
    
    
    // 加载用户数据
    private func loadUserInfo(response:AnyObject?,finished:((isSuccess: Bool) -> ())) {
        
        guard let result = response as? [String : AnyObject] else {
            
            finished(isSuccess: false)
            return
        }
        
        
        KKNetworkTools.sharedTools.loadUserInfo(result) { (responseObject, error) in
            if error != nil {
                print(error)

                finished(isSuccess: false)
                return
            }
        
            guard var dict = responseObject as? [String : AnyObject] else {
        
                finished(isSuccess: false)
                return
            }
            
            // 保存用户信息 合并两个字典
            for(key,value)in result {
                dict[key] = value
            }
            
            self.saveUserInfo(dict)
            
            finished(isSuccess: true)
            
        }
        
    }
}


extension KKUserAccountViewModel {
    
    /// 保存数据
    func saveUserInfo(dict:[String : AnyObject]) {
        
        // 字典转模型
        let userAccount = KKUserAccount.init(dict: dict)
        // MARK: 为了 解决 从 未登录状态 -> 登陆状态 userAccount 为nil 的bug
        self.userAccount = userAccount
        
        // 模型转字典
        let keys = ["access_token","expires_in","uid","avatar_large","name","expires_date"]
        let userInfo = userAccount.dictionaryWithValuesForKeys(keys)
        print(userInfo)
        
        // 使用偏好设置保存字典数据
        let userDefaults = NSUserDefaults.standardUserDefaults()
        userDefaults.setObject(userInfo, forKey: userInfoKey)
        userDefaults.synchronize()
        print(NSHomeDirectory())
    }
    
    
    /// 读取数据
    func loadUserAccount() -> KKUserAccount? {
        
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else {
            
            return nil
        }
        
        let userAccount = KKUserAccount.init(dict: dict)
        
        return userAccount
        
    }
    
    
}
